package com.eastedu.controller;

import cn.hutool.core.collection.ListUtil;
import com.eastedu.converter.ChapterNodeMapConverter;
import com.eastedu.easyexcel.reader.ExcelSheetReader;
import com.eastedu.easyexcel.util.ExcelUtil;
import com.eastedu.model.ktree.ChapterNodeMapVO;
import com.eastedu.repository.ktree.mapper.ChapterNodeMapMapper;
import com.eastedu.repository.ktree.po.ChapterNodeMapPO;
import com.google.common.collect.ImmutableList;
import lombok.SneakyThrows;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 章节树数据同步
 *
 * @author 张志帅
 */
@RestController
@RequestMapping(value = "/api/v1/ktree-service/data-sync")
public class KtreeServiceDataSyncController {

    private final ChapterNodeMapMapper chapterNodeMapMapper;
    private final ChapterNodeMapConverter chapterNodeMapConverter;

    public KtreeServiceDataSyncController(ChapterNodeMapMapper chapterNodeMapMapper,
                                          ChapterNodeMapConverter chapterNodeMapConverter) {
        this.chapterNodeMapMapper = chapterNodeMapMapper;
        this.chapterNodeMapConverter = chapterNodeMapConverter;
    }


    /**
     * 1. 章节树节点映射关系。
     * 2. 清理线上搜索服务和同步服务redis缓存，才会生效。
     * 3. 全量同步所有资源，确保历史数据生效。
     *
     * @return the http entity
     */
    @SneakyThrows
    @PostMapping("/chapter-node-mapping")
    public HttpEntity<Boolean> handle(@RequestParam MultipartFile file) {
        ExcelSheetReader<ChapterNodeMapVO> sheet0 = ExcelSheetReader.of(0, (data, hasError) -> consumer(data), ChapterNodeMapVO.class);
        ExcelUtil.read(file.getInputStream(), ImmutableList.of(sheet0));
        return ResponseEntity.ok(true);
    }

    private void consumer(List<ChapterNodeMapVO> vos) {
        ListUtil.partition(vos, 200).forEach(this::save);
    }

    private void save(List<ChapterNodeMapVO> chapterNodeMapVoList) {
        List<ChapterNodeMapPO> chapterNodeMapPoList = this.chapterNodeMapConverter.vo2po(chapterNodeMapVoList);
        this.chapterNodeMapMapper.insertBatchSomeColumn(chapterNodeMapPoList);
    }

}
